#include "GetBack.h"
#include "ui_GetBack.h"
#include"HttpManage.h"
#include"Global.h"
#include<QFile>
GetBack::GetBack(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GetBack)
{
    ui->setupUi(this);
    //设置初始头像
    ui->LogoLabel->setPixmap(QPixmap(":/assets/cloud_gold.png").scaled((ui->LogoLabel->size()),Qt::IgnoreAspectRatio,Qt::SmoothTransformation));
    //设置qss样式
    QFile file(":/assets/RegisterWidget.qss");
    if(file.open(QFile::OpenModeFlag::ReadOnly))
    {
        this->setStyleSheet(file.readAll());
        file.close();
    }
    else
    {
        qDebug("read qss failed\n");
    }
    //设置窗口图标
    QIcon icon(":/assets/cloud_red.png");
    this->setWindowIcon(icon);

    //连接getback相关信号和注册处理回调
       connect(HttpManage::GetInstance().get(), &HttpManage::sig_getback_mod_finish, this,&GetBack::slot_getback_mod_finish);
       InitHttpHandlers();
}

GetBack::~GetBack()
{
    delete ui;
}

void GetBack::slot_getback_mod_finish(ReqId id, QString res, ErrorCode err)
{
    if(err != ErrorCode::SUCCESS)
    {
        ShowTip(tr("网络请求错误"),false);
        return;
    }
    // 解析 JSON 字符串,res需转化为QByteArray
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    //json解析错误
    if(jsonDoc.isNull())
    {
        ShowTip(tr("json解析错误"),false);
        return;
    }
    //json解析错误
    if(!jsonDoc.isObject())
    {
        ShowTip(tr("json解析错误"),false);
        return;
    }
    //调用对应的逻辑,根据id回调。
    _handlers[id](jsonDoc.object());

    return;
}
void GetBack::ShowTip(QString str,bool is_ok)
{
    if(is_ok)
    {
        ui->HintLabel->setProperty("state","normal");
    }
    else
    {
        ui->HintLabel->setProperty("state","err");
    }
    ui->HintLabel->setText(str);
    repolish(ui->HintLabel);
}
void GetBack::InitHttpHandlers()
{
    //注册获取验证码回包逻辑
        _handlers.insert(ReqId::ID_GET_VERIFY_CODE, [this](QJsonObject jsonObj)
        {
            int error = jsonObj["error"].toInt();
            if(error != ErrorCode::SUCCESS)
            {
                ShowTip(tr("参数错误"),false);
                return;
            }
            auto email = jsonObj["email"].toString();
            ShowTip(tr("验证码已发送到邮箱，注意查收"), true);
            qDebug()<< "email is " << email ;
        });

        //注册重置密码用户回包逻辑
        _handlers.insert(ReqId::ID_GET_BACK, [this](QJsonObject jsonObj)
        {
            int error = jsonObj["error"].toInt();
            if(error != ErrorCode::SUCCESS)
            {
                ShowTip(tr("参数错误"),false);
                return;
            }
            auto email = jsonObj["email"].toString();
            ShowTip(tr("重置成功,点击返回登录"), true);
            qDebug()<< "email is " << email ;
        });
}

void GetBack::on_GetVerifyPushButton_clicked()
{
    qDebug()<<"receive verify btn clicked ";
    auto email = ui->EmailLineEdit->text();

    QRegularExpression regex(R"(^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$)");
    bool is_match = regex.match(email).hasMatch();
    if(is_match)
    {
        ShowTip(tr("验证码发送成功"),true);
        //发送验证码
        QJsonObject json_obj;
        json_obj["email"] = email;
        HttpManage::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_verifycode"),json_obj,ReqId::ID_GET_VERIFY_CODE,Modules::GETBACK);
    }
    else
    {
        ShowTip(tr("邮箱地址不正确"),false);
    }
}


void GetBack::on_AffirmPushButton_clicked()
{
    if(ui->UserLineEdit->text() == "")
    {
        ShowTip(tr("用户名不能为空"),false);
        return;
    }
    if(ui->EmailLineEdit->text() == "")
    {
        ShowTip(tr("邮箱不能为空"),false);
        return;
    }
    if(ui->PwdLineEdit->text() == "")
    {
        ShowTip(tr("密码不能为空"),false);
        return;
    }
    if(ui->ConfirmPwdLineEdit->text() == "")
    {
        ShowTip(tr("确认密码不能为空"),false);
        return;
    }
    if(ui->PwdLineEdit->text() != ui->ConfirmPwdLineEdit->text())
    {
        ShowTip(tr("密码和确认密码不匹配"),false);
        return;
    }
    if(ui->VerifyKeyLineEdit->text() == "")
    {
        ShowTip(tr("验证码不能为空"),false);
        return;
    }
    QJsonObject json_obj;
    json_obj["user"] = ui->UserLineEdit->text();
    json_obj["email"] = ui->EmailLineEdit->text();
    json_obj["passwd"] = md5Encrypt(ui->PwdLineEdit->text());
    json_obj["confirm"] = md5Encrypt(ui->ConfirmPwdLineEdit->text());
    json_obj["verifycode"] = ui->VerifyKeyLineEdit->text();
    HttpManage::GetInstance()->PostHttpReq(QUrl(gate_url_prefix+"/get_back"),json_obj, ReqId::ID_GET_BACK,Modules::GETBACK);
}
